#include <iostream>
#include <websocketpp/server.hpp>
#include <websocketpp/config/asio_no_tls.hpp>
#include <functional>
#include <string>

typedef websocketpp::server<websocketpp::config::asio> wsserver_t;

void open_callback(wsserver_t *pwssrv,websocketpp::connection_hdl hdl)
{
    std::cout << "Websocket握手成功!" << std::endl;
}

void close_callback(wsserver_t *pwssrv,websocketpp::connection_hdl hdl)
{
    std::cout << "Websocket断开成功!" << std::endl;
}

void http_callback(wsserver_t *pwssrv,websocketpp::connection_hdl hdl)
{
    //1. 获取一个连接对象指针
    wsserver_t::connection_ptr conn = pwssrv->get_con_from_hdl(hdl);
    //2. 输出请求正文
    std::cout << "body: " << conn->get_request_body() << std::endl;
    //3. 输出请求方法和uri
    websocketpp::http::parser::request rps = conn->get_request();
    std::cout << "method: " << rps.get_method() << std::endl;
    std::cout << "uri: " << rps.get_uri() << std::endl;
    //4. 给一个响应
    std::string body = "<html><body><h1>Hello World</h1></body></html>";
    conn->set_body(body);
    conn->append_header("Content-Type","text/html");
    conn->set_status(websocketpp::http::status_code::ok);
}
void message_callback(wsserver_t *pwssrv,websocketpp::connection_hdl hdl,wsserver_t::message_ptr msg)
{
    //1. 输出客户端发送过来的信息(获取有效载荷)
    std::cout << "message: " << msg->get_payload() << std::endl;
    //2. 给一个响应
    wsserver_t::connection_ptr conn = pwssrv->get_con_from_hdl(hdl);
    std::string rps = "Server say: " + msg->get_payload();
    conn->send(rps);
}
int main()
{
    //1. 创建server对象
    wsserver_t wsserver;
    //2. 设置日志等级
    wsserver.set_access_channels(websocketpp::log::alevel::none);
    //3. 初始化asio调度器
    wsserver.init_asio();
    wsserver.set_reuse_addr(true);
    //4. 设置回调函数
    wsserver.set_open_handler(bind(open_callback,&wsserver,std::placeholders::_1));
    wsserver.set_close_handler(bind(close_callback,&wsserver,std::placeholders::_1));
    wsserver.set_http_handler(bind(http_callback,&wsserver,std::placeholders::_1));
    wsserver.set_message_handler(bind(message_callback,&wsserver,std::placeholders::_1,std::placeholders::_2));
    //5. 设置监听端口
    wsserver.listen(8080);
    //6. 获取新连接
    wsserver.start_accept();
    //7. 服务器运行
    wsserver.run();
    return 0;
}